package com.hancheng.commoncloud.framework.config;

import io.micrometer.core.instrument.util.NamedThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Component;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author 金笛
 * @date 2022/1/23 16:05
 * @Description: 线程池
 **/
@Component
public class AsyncConfig implements SchedulingConfigurer {

    /**
     * @author: 业务逻辑使用的线程池
     * @Date: 2020/8/23 9:45
     * @Description: 创建线程池对象
     **/
    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {
        return new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors() + 1, Runtime.getRuntime().availableProcessors() * 2,
                60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(500),
                new NamedThreadFactory("bridge-thread"), new ThreadPoolExecutor.CallerRunsPolicy());
    }

    /**
     * @param scheduledTaskRegistrar
     * @Scheduled 新增定时调度任务必须定时任务线程 +1 防止由于定时任务线程池剩余线程不足导致串行执行
     * 定时任务使用的线程池
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(10);
        scheduler.setThreadNamePrefix("task-");
        scheduler.setAwaitTerminationSeconds(600);
        scheduler.setWaitForTasksToCompleteOnShutdown(true);
        scheduler.initialize();
        scheduledTaskRegistrar.setTaskScheduler(scheduler);
    }
}
